Computer Science 161.01

Oct 22 and 24

 

JavaScript loops

 

 

 

The while statement in JavaScript

 

The real power of programming in a high-level language comes with the ability to write loops. Once we can write loops, we can solve many types of problems.

We become dangerous in that sense!  We also can suddenly do amazing things – like simulate 1000 tosses of a pair of dice and see how many 7’s are rolled.

Or like sorting having a list of 10000 names (or numbers, for that matter) sorted!  This is the real reason we use computers, because of their power and speed.

 

One way to write a loop in JavaScript is with the while statement. 

Its syntax is surprisingly like that of the Javascript if statement, except that for the one key word.

 

//JAVASCRIPT while STATEMENT SYNTAX

// while (Boolean expression ) {

//     statement(s)

// }

 

The word while should suggest to you repetition as in “so long as”.

 

An example (a variant of our first if statement example) should illustrate the semantics:

 

x = 9;

while (x > 2) {

     alert(x + " is a really big number");

     x = x – 2;

}    

alert(" good-bye " + x);

 

 

So how does this work, you might ask?

Try this in the scratchpad.

 

First, of course x gets assigned 9.

JavaScript then evaluates (x > 2) as true.

Since it is true , it will go in to the loop and do the statements within:

      1. It will pop-up an alert box that says  9 is a really big number.

   2. It will do x = x – 2 causing x to become 7.

 

Now, JavaScript re-evaluates (x > 2) as true.

That means we’re allowed in again – great!

So we say  7 is a really big number and then x becomes 5 .

Back we go again,  checking (x > 2) saying 5 is a really big number then x becomes 3 .

One more time:  Back again, checking  (x > 2) saying 3 is a really big number then x becomes 1.

Back again, checking  (x > 2) gives us (finally) false .  We’re not allowed in to do those two actions this time.

 

Where to now??? 

To the  alert statement following the while loop: it will say   good-bye 1 .

 

 

Writing a Loop to Count

 

Often, we have something that we know works and are particularly proud of.

 

For example, I enjoy the following 1-line program a great deal:

alert("Tom is great!");

 

What I really want is a program that would do this a specified number of times.

That is, I want this done, say 10 times:    alert("Tom is great!");

 

My problem then is getting JavaScript to understand how many times it has performed a certain action.

You see, the program itself must keep count of how many times it has done something!

So it will just need to be counting along, just as you and I would be if we were writing

Tom is great!  10 times on the white board!

 

The program can track this in some variable which we might conveniently name count.

 

The program should start by assigning count the value 0 :    count = 0;

(After all, it hasn’t written the message yet!)

 

Now, whenever, the program does    alert("Tom is great!");

it should also note one more occurrence by doing  count++;

thereby increasing count by 1 more.

 

And we want to keep doing this another time so long as (or  while)

count remains less than 10.  (Think of getting to 10 as its goal in some sense).

 

Let’s see what we have now:

 

count = 0;

 

while (count < 10) {         //haven’t met our goal yet

   alert("Tom is great!");   //do what it is you want repeated…

   count++;                  //notch 1 more occurrence

}

 

Try this in the scratchpad.

 

In case you’re wondering, the ordering of these two statements does not matter here:

   alert("Tom is great!");  

   count++;                 

 

We’ll still get the message shown 10 times!

 

When we write a loop to do something some specified number of times (say n times),

we’ll refer to this as definite iteration (because the program has a definite number of times in mind).

 

 

Our Pattern for Definite Iteration

 

For definite iteration, we’ll know we can use this basic pattern:

 

//do something n times

 

count = 0;

  

while (count < n) { 

   //do something

   count++;                  //notch 1 more occurrence

}

 

In this model,   //do something can be replaced by however many statements are needed to accomplish the task.

 

 

 

Writing a Loop for Indefinite Iteration

 

You might be saying “Hey, wait a second, other people are great as well”.

In which case, you might want to have a program that asks for one name at a time.

              name = prompt("Who is great?");  

 

and indicates for each name entered that the person named is great:

              alert(name + " is great!");  

 

I would like the program to keep doing this so long as I do not enter the word STOP.

 

This looks like a good idea at first but it has its issues:

              while (name != "STOP") { 

                   name = prompt("Who is great?");

                   alert(name + " is great!");  

              }

 

Try this in the scratchpad.

What were the issues?

 

You see, name hasn’t gotten anything in it when the first alert(name + " is great!");

is trying to do its thing.  So we don’t see anything and the program chokes right there!

 

Let’s try fixing this by putting name = prompt("Who is great?");   above the loop:

 

                       name = prompt("Who is great?");

 

                        while (name != "STOP") { 

                   name = prompt("Who is great?");

                   alert(name + " is great!");  

              }

 

Try this in the scratchpad.

Now it’s really screwed up .   Why?

Well, first, it ignores the first name I enter.

Then it has the audacity to say  STOP is great!

That’s right… nobody wants to see    STOP is great!

 

We could fix that by switch the order of the two statements within the loop:

 

                        name = prompt("Who is great?");

 

                        while (name != "STOP") { 

                   alert(name + " is great!");

                   name = prompt("Who is great?");

            }

 

Did this work?  You bet!!

 

In retrospect, this makes a lot of sense.

 

You see, you need the initial prompt in order for the  while condition to make sense the 1st time.

You need the other prompt exactly where it is so that it captures STOP just in time, and doesn’t allow the

program to say STOP is great!

 

 

Our Pattern for InDefinite Iteration

 

We’re seeing another pattern here, for indefinite iteration that allows us to enter a series of values

(whether they be strings or numbers or colors or whatever) until some stopping condition is met

(or, in other words, so long as some stopping condition is not met).

 

So, if you want to read in a series of numbers and display them, but stop as soon as a negative number

is entered, this would suffice:

 

num = prompt("Enter a number");

 

while (num >= 0) { 

                   alert(num + " is not negative!");

                   num = prompt("Enter another: ");

            }

 

Note the similarity to the prior example.

Then try it in the scratchpad.

 

 

One final example that fits this mold is too much fun to resist.

Hopefully you will agree and try it in the scratchpad.

Convince yourself that this is the same pattern for indefinite iteration that we saw previously.

 

yourColor = prompt("Enter a color");

 

while (yourColor != "black") {

       document.bgColor = yourColor; 

                   alert("Your color is not black!");

                   yourColor = prompt("Enter another: ");

            }

 

                        document.bgColor = yourColor; 

            alert("Now THAT is black!");

            document.bgColor = "#ffdab9"; //original color